<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>vue视图异步更新原理</title>
  <style>
      #app {
          width: 200px;
          margin: auto;
      }
  </style>
</head>
<body>
<div id="app">
  <button id="btn">count++</button>
  <div id="el"></div>
</div>
<script>
  let activeEffect = null

  const el = document.getElementById('el')
  const btn = document.getElementById('btn')

  function effect(fn) {
    activeEffect = fn
    fn()
    activeEffect = null
  }

  const set = new Set()

  const tasks = new Set()

  function runTasks() {
    Promise.resolve().then(() => {
      tasks.forEach(task => task())
      tasks.clear()
    })
  }

  const count = {
    _value: 0,
    get value() {
      activeEffect && set.add(activeEffect)
      return this._value
    },
    set value(newValue) {
      this._value = newValue
      // 触发视图更新
      // set.forEach((cb) => cb())
      set.forEach((cb) => tasks.add(cb))
      runTasks()
      nextTick(() => {
        console.log(this._value)
      })
    }
  }

  effect(() => {
    console.log('view update')
    el.innerText = count.value
  })

  function nextTick(cb) {
    Promise.resolve().then(cb)
  }

  btn.addEventListener('click', () => {
    count.value++
    count.value++
  })
</script>
</body>
</html>
